
package com.j2eefast.bussiness.contract.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.j2eefast.bussiness.contract.entity.BusDepreciationEntity;
import com.j2eefast.bussiness.contract.entity.BusStandardEntity;
import com.j2eefast.bussiness.contract.entity.PaySetEntity;
import com.j2eefast.bussiness.contract.service.BusClassifyService;
import com.j2eefast.bussiness.contract.service.BusInstallsService;
import com.j2eefast.bussiness.contract.service.BusStandardService;
import com.j2eefast.bussiness.contract.service.PaySetService;
import com.j2eefast.bussiness.contract.utils.MonthSheetWriteHandler;
import com.j2eefast.common.core.base.entity.Ztree;
import com.j2eefast.common.core.business.annotaion.BussinessLog;
import com.j2eefast.common.core.controller.BaseController;
import com.j2eefast.common.core.enums.BusinessType;
import com.j2eefast.common.core.utils.ResponseData;
import com.j2eefast.common.core.utils.ToolUtil;
import com.j2eefast.common.core.utils.ValidatorUtil;
import com.j2eefast.framework.annotation.RepeatSubmit;
import com.j2eefast.framework.utils.Global;
import com.j2eefast.framework.utils.UserUtils;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * <p>工资账套</p>
 *
 * @author: summer
 * @date: 2021-06-06 14:41
 * @web: http://www.letukeji.cn
 * @version: 1.0.1
 */
@Controller
@RequestMapping("/bus/standard")
public class BusStandardController extends BaseController {

	private String urlPrefix = "modules/bus/standard";
	@Autowired
	private BusStandardService pusStandardService;
	@Autowired
	private BusInstallsService busInstallsService;
	@Autowired
	private BusClassifyService busClassifyService;

	@RequiresPermissions("bus:standard:view")
	@GetMapping()
	public String process() {
		return urlPrefix + "/index";
	}

//	@RequestMapping("/list")
//	@RequiresPermissions("bus:set:list")
//	@ResponseBody
//	public ResponseData list(@RequestParam Map<String, Object> params) {
//		PageUtil page = paySetService.findPage(params);
//		return success(page);
//
//	}
	/**
	 * 页面获取公司信息列表
	 * @param params
	 * @return
	 */
	@RequestMapping("/list")
	@RequiresPermissions("bus:standard:list")
	@ResponseBody
	public List<BusStandardEntity> list(@RequestParam Map<String, Object> params) {
		return  pusStandardService.findList(params);
	}

	/**
	 * 加载公司列表树
	 */
	@GetMapping("/treeData")
	@RequiresPermissions("bus:standard:list")
	@ResponseBody
	public List<Ztree> treeData(Long parentId){
		List<Ztree> ztrees = pusStandardService.findCompTree(parentId);
		return ztrees;
	}


	/**
	 * 删除
	 */
//	@BussinessLog(title = "删除", businessType = BusinessType.DELETE)
//	@RequestMapping( value = "/del", method = RequestMethod.POST)
//	@RequiresPermissions("bus:set:del")
//	@RequiresRoles(Constant.SU_ADMIN)
//	@ResponseBody
//	public ResponseData delete(Long[] ids) {
//		System.out.println("122222222");
//		System.out.println("122222222");
//		System.out.println("122222222");
//		return paySetService.deleteByIds(ids)?success(): error("删除失败!");
//	}

//	/**
//	 * 删除公司
//	 */
//	@BussinessLog(title = "删除", businessType = BusinessType.DELETE)
//	@RequestMapping("/del/{id}")
//	@RequiresPermissions("bus:set:del")
//	@ResponseBody
//	public ResponseData delete(@PathVariable("id") Long id) {
//
//		//busClassifyService.checkDataScope(compId);
//
//
//		if(pusStandardService.delSysCompById(id)) {
//			return success();
//		}else {
//			return error("删除失败!");
//		}
//	}

	/**
	 * 工资账套删除
	 */
	@RepeatSubmit
	@RequiresPermissions("pms:standard:del")
	@BussinessLog(title = "删除", businessType = BusinessType.UPDATE)
	@RequestMapping(value = "/del", method = RequestMethod.POST)
	@ResponseBody
	public ResponseData doDelete(HttpServletRequest request) {
		Long  ids=Long.parseLong(request.getParameter("id")) ;
		return pusStandardService.delSysCompById(ids) ? success() : error("删除失败!");
	}




	/**
	 * 修改出入库 页面
	 */
	@RequiresPermissions("bus:standard:edit")
	@GetMapping("/edit/{id}")
	public String edit(@PathVariable("id") Long id, ModelMap mmap) {
		System.out.println(id);
        BusStandardEntity busStandardEntity = pusStandardService.findCompById(id);
		System.out.println(busStandardEntity.getStandardName());
		mmap.put("standard", busStandardEntity);

		return urlPrefix + "/edit";
	}

	/**
	 * 修改出入库保存
	 */
	@RepeatSubmit
	@RequiresPermissions("bus:standard:edit")
	@BussinessLog(title = "修改", businessType = BusinessType.UPDATE)
	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	@ResponseBody
	public ResponseData edit(BusStandardEntity busStandardEntity) {
		ValidatorUtil.validateEntity(busStandardEntity);
		Date date = new Date();//创建一个时间对象，获取到当前的时间
        busStandardEntity.setUpdateTime(date);
//		Long userId= UserUtils.getUserInfo().getId();
//		SysUserEntity sysUserEntity=busEquipmentService.getSysById(userId);
//		busEquipmentEntity.setUpdateBy(sysUserEntity.getName());
		String userName=UserUtils.getUserInfo().getName();
        busStandardEntity.setCreateBy(userName);
		System.out.println("修改出入库保存");
		System.out.println("修改出入库保存");
		System.out.println("修改出入库保存");
		System.out.println("修改出入库保存");
		return pusStandardService.updateById(busStandardEntity) ? success() : error("修改失败!");
	}

//	/**
//	 * 新增参数配置
//	 */
//	@RequiresPermissions("bus:standard:add")
//	@GetMapping("/add")
//	public String add() {
//		System.out.println("222222222222222");
//		return urlPrefix + "/add";
//	}

	/**
	 * 新增参数配置
	 */
	@GetMapping("/add/{id}")
	public String add(@PathVariable("id") Long id, ModelMap mmap){

		//mmap.put("comp",  busClassifyService.findCompById(id));
        BusStandardEntity busStandardEntity = pusStandardService.findCompById(id);
		mmap.put("standard",  busStandardEntity);
		return urlPrefix + "/add";
	}



	/**
	 * 新增保存
	 */
	@RepeatSubmit
	@RequiresPermissions("bus:standard:add")
	@BussinessLog(title = "信息", businessType = BusinessType.INSERT)
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public ResponseData addSave(@Validated  BusStandardEntity busStandardEntity) {
		//校验参数
		ValidatorUtil.validateEntity(busStandardEntity);
		Date date = new Date();//创建一个时间对象，获取到当前的时间
		//SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//注意月份是MM
        busStandardEntity.setCreateTime(date);
		String userName=UserUtils.getUserInfo().getName();
        busStandardEntity.setCreateBy(userName);
//        busStandardEntity.setParentId(1L);
		return pusStandardService.save(busStandardEntity) ? success() : error("新增失败!");
	}


	@BussinessLog(title = "报废导出", businessType = BusinessType.EXPORT)
	@RequiresPermissions("bpm:standard:export")
	@PostMapping("/export")
	@ResponseBody
	public ResponseData export(@RequestParam Map<String, Object> params) throws Exception {
		WriteCellStyle headWriteCellStyle = new WriteCellStyle();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分");
		String date = sdf.format(new Date());
		String fileName =  "报废";
		fileName = ToolUtil.encodingExcelFilename(fileName);
		String folder = Global.getTempPath() + File.separator + "pio" + File.separator;
		List<BusStandardEntity> listData = pusStandardService.findList(params);
		//内容样式策略
		WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
		//垂直居中,水平居中
		contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
		contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
		contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
		contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
		contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
		contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
		//设置 自动换行
		contentWriteCellStyle.setWrapped(true);
		// 字体策略
		WriteFont contentWriteFont = new WriteFont();
		// 字体大小
		contentWriteFont.setFontHeightInPoints((short) 12);
		contentWriteCellStyle.setWriteFont(contentWriteFont);
		//头策略使用默认

		EasyExcel.write(folder + fileName, BusDepreciationEntity.class)
				//设置输出excel版本,不设置默认为xlsx
				//.excelType(ExcelTypeEnum.XLS).head(ProjectSanLianEntity.class)
				//设置拦截器或自定义样式
				.registerWriteHandler(new MonthSheetWriteHandler())
				.registerWriteHandler(new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle))
				.sheet("报废查询")
				//设置默认样式及写入头信息开始的行数
				.useDefaultStyle(true).relativeHeadRowIndex(3)
				//这里的addsumColomn方法是个添加合计的方法,可删除
				.doWrite(listData);

		return success(fileName);
	}




//	/**
//	 * 导入
//	 */
//	@RequiresPermissions("bpm:depreciation:import")
//	@BussinessLog(title = "折旧管理", businessType = BusinessType.IMPORT)
//	@PostMapping("/import")
//	@ResponseBody
//	public ResponseData importSanLianSave(@RequestParam Map<String, Object> tables){
//		String[] tableNames = Convert.toStrArray(tables.get("tables"));
//		for(int i=0;i<tableNames.length;i++){
//			System.out.println(tableNames[i]);
//		}
//		String dbName = (String) tables.get("dbName");
////		SysDatabaseEntity db = sysDatabaseService.getByName(dbName);
////		// 查询表信息
////		List<GenTableEntity> tableList = genTableService.generateDbTableListByNames(db, tableNames);
////		genTableService.importGenTable(tableList, UserUtils.getLoginName(),dbName);
//		return success();
//	}


	/**
//	 * 上传excel
//	 */
//	@BussinessLog(title = "上传文件", businessType = BusinessType.UPDATE)
//	@PostMapping("/upload")
//	@RequiresPermissions("bpm:depreciation:upload")
//	@RepeatSubmit
//	@ResponseBody
//	public ResponseData upload(@RequestParam("files") MultipartFile file){
//		try{
//			if (!file.isEmpty()){
//				String pathName = FileUploadUtil.uploadFile(Global.getTempPath(), file);
//				//	Map<String,String> res = new HashMap<>();
//				//	int row=1;			//通过该字段标记在导入第几行
//				int rowSuccess=0;		//标记成功导入的数据条数
//				//	QueryWrapper<ProjectSanLianEntity> wrapper;		//mybatis-plus自带的筛选查询
//				//        ReadExcel readExcel = new ReadExcel();
//				List<BusDepreciationEntity> excelInfo = ReadPatientExcelUtil.getExcelInfo(file,pathName);		//调用工具类，传入excel文件，得到数组对象
//				for (BusDepreciationEntity patientInfo : excelInfo) {
//					//	System.out.println("111111111");
//					//wrapper=new QueryWrapper<>();
//					//	row++;		//遍历插入
//					//	System.out.println(patientInfo.getName());
//
//					int patientCount =busDepreciationService.getDepreciationInfo(patientInfo.getId());
//					if (patientCount>0){//如果大于零表示已存在
//						//sanLianService.updateByIds(patientInfo);
//					}else {
//						System.out.println("444444");
//						boolean save = busDepreciationService.save(patientInfo);
//						//如果不存在，将数据道存到数据库
//						if (save){
//							rowSuccess++;		//保存成功后，成功数+1
//						}
//					}
//				}
//				return success();
//			}
//			return error(ToolUtil.message("sys.file.null"));
//		}
//		catch (Exception e)
//		{
//			System.out.println(e);
//			return error("c出错误了"+e);
//		}
//
//
//	}







}
